package com.itjcloud.iot.gateway.filter.global;

import com.itjcloud.iot.gateway.model.CommonTokenInfo;
import com.itjcloud.iot.gateway.service.ItjJwtDecoderService;
import com.itjcloud.iot.gateway.tools.AuthorizationRequestTool;
import com.itjcloud.iot.gateway.tools.JwtTool;
import io.micrometer.common.lang.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 校验用户的jwt token 然后把jwt中获取的数据添加到请求头中
 */
@RequiredArgsConstructor
@Component
@Order(0)
public class VerifyJsonWebTokenFilter implements GlobalFilter {

    private final ItjJwtDecoderService itjJwtDecoderService;

    @Override
    @NonNull
    public Mono<Void> filter(@NonNull ServerWebExchange exchange, GatewayFilterChain chain) {


        return Mono.just(exchange).map(ServerWebExchange::getRequest)
                .map(HttpMessage::getHeaders)
                .mapNotNull(item -> item.get(HttpHeaders.AUTHORIZATION))
                //如果没有token继续放行
                .flatMap(list -> list.stream().findFirst().map(Mono::just).orElseGet(Mono::empty))
                //去除Bearer. 并判断是否是Bearer
                .flatMap(AuthorizationRequestTool::extractHeaderToken)
                .flatMap(item -> JwtTool.isJwt(item) ? Mono.just(item) : Mono.empty())
                //判断jwt是否正确并解析信息
                .flatMap(itjJwtDecoderService::getPayloadToUserInfo)
                //获取用户信息并添加上下文中. 最后转发的时候添加到请求头
                .doOnNext(item -> exchange.getAttributes().put(CommonTokenInfo.class.getName(), item))
                .then(chain.filter(exchange));
    }


}
